package org.dromara.book.controller;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.book.controller.form.SzlyBookInventoryAddBo;
import org.dromara.book.util.BarCodeUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.book.domain.vo.SzlyBookInventoryVo;
import org.dromara.book.domain.bo.SzlyBookInventoryBo;
import org.dromara.book.service.ISzlyBookInventoryService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 图书库存
 * 前端访问路由地址为:/book/bookInventory
 *
 * @author LionLi
 * @date 2024-03-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/bookInventory")
public class SzlyBookInventoryController extends BaseController {

    private final ISzlyBookInventoryService szlyBookInventoryService;

    /**
     * 查询图书库存列表
     */
    @SaCheckPermission("book:bookInventory:list")
    @GetMapping("/list")
    public TableDataInfo<SzlyBookInventoryVo> list(SzlyBookInventoryBo bo, PageQuery pageQuery) {
        return szlyBookInventoryService.queryPageList(bo, pageQuery);
    }

    /**
     * 根据isbn查询图书
     */
    @GetMapping("/listByIsbnId")
    public R<List<SzlyBookInventoryVo>> listByIsbnId(Long isbnId) {
        SzlyBookInventoryBo bookInventoryBo = new SzlyBookInventoryBo();
        bookInventoryBo.setIsbnId(isbnId);
        return R.ok(szlyBookInventoryService.queryList(bookInventoryBo));
    }

    /**
     * 导出图书库存列表
     */
    @SaCheckPermission("book:bookInventory:export")
    @Log(title = "图书库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SzlyBookInventoryBo bo, HttpServletResponse response) {
        List<SzlyBookInventoryVo> list = szlyBookInventoryService.queryList(bo);
        ExcelUtil.exportExcel(list, "图书库存", SzlyBookInventoryVo.class, response);
    }

    /**
     * 获取图书库存详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("book:bookInventory:query")
    @GetMapping("/{id}")
    public R<SzlyBookInventoryVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(szlyBookInventoryService.queryById(id));
    }

    /**
     * 图书入库
     */
    @SaCheckPermission("book:bookInventory:add")
    @Log(title = "图书库存", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<CharSequence> add(@Validated(AddGroup.class) @RequestBody SzlyBookInventoryAddBo bo) {
        String barCode = bo.getBarCode();
        Long number = BarCodeUtil.getNumber(barCode);
        String old = String.valueOf(BarCodeUtil.getNumber(barCode));
        Integer oldLength = BarCodeUtil.getBarCodeNumberLength(barCode);
        Integer num = bo.getNum();
        for (Integer i = 0; i < num; i++) {
            String newN = String.valueOf(number);
            SzlyBookInventoryBo inventoryBo = new SzlyBookInventoryBo();
            inventoryBo.setBarCode(barCode.replace(StrUtil.padPre(old, oldLength,"0")
                ,StrUtil.padPre(newN,Math.max(newN.length(),oldLength),"0")));
            inventoryBo.setInTime(LocalDateTime.now());
            inventoryBo.setStatus("in");
            inventoryBo.setLocationId(bo.getLocationId());
            inventoryBo.setBatchId(bo.getBatchId());
            inventoryBo.setPriceReal(bo.getPriceReal());
            inventoryBo.setIsbnId(bo.getIsbnId());
            inventoryBo.setShelfId(bo.getShelfId());
            number++;
            List<SzlyBookInventoryVo> list = szlyBookInventoryService.queryByBarCode(inventoryBo.getBarCode());
            if(!list.isEmpty()){
                return R.fail("条形码重复，不能新增");
            }
            szlyBookInventoryService.insertByBo(inventoryBo);
        }
        String newN = String.valueOf(number);
        return R.ok((CharSequence)barCode.replace(StrUtil.padPre(old, oldLength,"0")
            ,StrUtil.padPre(newN,Math.max(newN.length(),oldLength),"0")));
    }

    /**
     * 修改图书库存
     */
    @SaCheckPermission("book:bookInventory:edit")
    @Log(title = "图书库存", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SzlyBookInventoryBo bo) {
        return toAjax(szlyBookInventoryService.updateByBo(bo));
    }

    /**
     * 删除图书库存
     *
     * @param ids 主键串
     */
    @SaCheckPermission("book:bookInventory:remove")
    @Log(title = "图书库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(szlyBookInventoryService.deleteWithValidByIds(List.of(ids), true));
    }
}
